package com.project.service.bloom;

import com.alibaba.fastjson2.JSON;
import com.project.entity.filter.SysUserFilter;
import com.project.entity.model.SysUserModel;
import com.project.repository.SysUserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Service
public class BloomFilterTestService {


    private static final String USER_CACHE_PREFIX = "user_cache";
    private static final String BLOOM_FILTER_NAME = "UserBloomFilter";

    @Autowired
    private SysUserRepository sysUserRepository;
    @Autowired
    private BloomFilterService bloomFilterService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostConstruct
    public void initUserBloom() {
        bloomFilterService.initBloomFilter(BLOOM_FILTER_NAME);
        List<SysUserModel> sysUserModels = sysUserRepository.listModel(SysUserFilter.newInstance());
        sysUserModels.forEach(a -> bloomFilterService.addToBloomFilter(BLOOM_FILTER_NAME, USER_CACHE_PREFIX + a.getKey()));
    }

    public SysUserModel getModel(Integer key) {
        String fullKey = USER_CACHE_PREFIX + key;

        boolean contains = bloomFilterService.mightContain(BLOOM_FILTER_NAME, fullKey);
        if (contains) {
            String value = stringRedisTemplate.opsForValue().get(fullKey);
            if (StringUtils.isNotEmpty(value)) {
                return JSON.parseObject(value, SysUserModel.class);
            }
        }
        return null;
    }


}
